package com.jochen.core.screen.transitions

import com.badlogic.gdx.Gdx
import com.jochen.core.screen.BaseScreen
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType
import com.jochen.core.screen.Transition
import kotlin.math.abs
import com.badlogic.gdx.math.Matrix4

class FadeTransition(
    private val shapeRenderer: ShapeRenderer,
    private val duration: Float = DEFAULT_DURATION
    ): Transition{
    
    companion object{
        private const val DEFAULT_DURATION = 0.5f
        private val DEFAULT_COLOR = Color.BLACK
    }
    private var time: Float = 0f
    private val TransitionColor: Color = DEFAULT_COLOR.cpy()
    val matrix = Matrix4().apply {
        setToOrtho2D(0f, 0f, Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat())
    }
    override fun update(delta: Float) { time += delta}
    override val isFinished get() = time >= duration
    
    override fun render(delta: Float, form: BaseScreen, to: BaseScreen) {
        val alpha = (time / duration).coerceIn(0f, 1f)
        if (alpha < 0.5f) form.render(delta) else to.render(delta)
        Gdx.gl.glEnable(GL20.GL_BLEND)
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)
        
        shapeRenderer.apply {
        begin(ShapeType.Filled)
            projectionMatrix = matrix
            TransitionColor.a = 1 - abs(alpha - 0.5f)
            setColor(TransitionColor)
            rect(0f, 0f, Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat())
            end()
        }
        Gdx.gl.glDisable(GL20.GL_BLEND)
        
    }
  
    override fun dispose(){}
    
    override fun onStart(){
        time = 0f
    }
}